package org.banyan.senior.idempotent.interceptor;

import com.alibaba.fastjson.JSON;
import org.banyan.senior.idempotent.annotation.AutoDuplicateRequest;
import org.banyan.senior.idempotent.bean.ResponseResult;
import org.banyan.senior.idempotent.util.RedisTokenUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

import static org.springframework.http.HttpStatus.OK;

/**
 * @author metalsbanyan
 * @version 1.0
 * @description: 接口短时间重复请求拦截器
 * @date 2023/7/21 11:22
 */

public class DuplicateRequestHandlerInterceptor implements HandlerInterceptor {



    @Value("${duplicate.request.times:5000}")
    private  long duplicateRequestTimes;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (support(handler)) {
            if (RedisTokenUtil.isDuplicateRequest(request)) {
                ResponseResult<Object> responseResult = ResponseResult.builder()
                        .code(OK.value())
                        .msg("不要频繁点击")
                        .build();
                response.setCharacterEncoding("utf-8");
                response.getWriter().println(JSON.toJSONString(responseResult));
                response.setContentType("application/json");
                response.setStatus(OK.value());
                System.err.println("不要频繁点击!!!!!");
                return false;
            }else {
                RedisTokenUtil.setDuplicateRequestCache(request, duplicateRequestTimes);
            }
        }
        return true;
    }


    private boolean support(Object handler) {

        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            boolean supported = handlerMethod.getBean().getClass().isAnnotationPresent(AutoDuplicateRequest.class);
            if (supported){
                return true;
            }
            Method method = handlerMethod.getMethod();
            return method.isAnnotationPresent(AutoDuplicateRequest.class);
        }
        return false;
    }

}